package StudySpringBoot2.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授权
    @Override
    protected void configure(HttpSecurity security) throws Exception {
        security.authorizeRequests().
                antMatchers("/").permitAll()   //任何人都可以访问首页
                .antMatchers("/level1/**").hasRole("vip1") //vip1等级的可以访问level1
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        // 自带登录页面，http://localhost:8080/login
        // 定制登录页，loginPage("/toLogin")
        // 指定表单提交url：loginProcessingUrl("/user/login")
        security.formLogin().loginPage("/toLogin")
                .usernameParameter("username").passwordParameter("password")
                .loginProcessingUrl("/login");
        // 开启注销功能,源码http://localhost:8080/logout，并且注销成功后跳转到/的Controller
        security.logout().logoutSuccessUrl("/");
        // 版本不同问题，可能会出现注销失败，关闭csrf
        // security.csrf().disable();
        // 开启记住我功能:本质就是记住一个cookies，默认保存2周
        security.rememberMe().rememberMeParameter("remember");
    }

    //认证
    @Override    //passwordEncoder(new BCryptPasswordEncoder()) 对密码进行加密，否则会报错
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //下边的数据应该从数据库中获取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("vip1", "vip2", "vip3")
                .and()
                .withUser("test").password(new BCryptPasswordEncoder().encode("test")).roles("vip1");
    }
}
